#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include <string.h>
#include <sys/unistd.h>
#include <sys/stat.h>
#include <time.h>
#include <stdio.h>
#include <sys/param.h>
#include <dirent.h>
#include "esp_log.h"
#include "esp_err.h"
#include "esp_event.h"
#include "esp_lvgl_port.h"
#include "esp_vfs_fat.h"
#include "sdmmc_cmd.h"
#include "driver/sdmmc_host.h"
#include "voice_recorder_ui.h"
#include "main_ui.h"
#include "audio_player.h"
#include "wifi_setting_ui.h"
#include "md_languages.h"
#include "ui_setting.h"
#include "audio.h"
#include "sd_card.h"
#include "format_wav.h"
#include "audio.h"
#include "app_sr.h"
#include "pca9557pw.h"

static const char *TAG = "voice_recorder";
#define VOICE_SD_PATH SD_MOUNT_POINT "/voice"

// 声明字体
LV_FONT_DECLARE(myFont);
LV_FONT_DECLARE(lv_font_montserrat_14);

// 全局变量
static lv_obj_t *waveform_chart;
static lv_obj_t *time_label;
static lv_obj_t *rec_button;
static lv_obj_t *list;
static uint32_t rec_seconds = 0;
static bool is_recording = false;
static lv_chart_series_t *ser;
static lv_timer_t *waveform_timer;
static lv_timer_t *new_file_timer;
static lv_obj_t *rec_label;
static lv_obj_t *current_list_btn;//当前点击的列表按钮


static TaskHandle_t voice_task_Handle = NULL;
static EventGroupHandle_t s_voice_event_group = NULL;


// 定义缓冲区大小常量
#define I2S_READ_BUFFER_SIZE 4096
// 事件组标志位定义
#define VOICE_START_BIT    BIT0
#define VOICE_STOP_BIT     BIT1
#define VOICE_EXIT_BIT     BIT2
#define VOICE_NEW_FILE_BIT BIT3
#define VOICE_PLAY_BIT     BIT4
#define VOICE_ALL_BITS     (VOICE_START_BIT | VOICE_STOP_BIT | VOICE_EXIT_BIT | VOICE_NEW_FILE_BIT | VOICE_PLAY_BIT)
//static bool is_voice_play = false;
// 文件路径和缓冲区
static char file_path[128] = { 0 };

// 存储最近创建的文件名，用于添加到列表
static char latest_filename[64] = { 0 };

// 函数声明
void destroy_voice_recorder_ui(void);
static void list_btn_event_cb(lv_event_t *e);
void exit_voice_recorder_ui(lv_obj_t *root)
{
    switch_to_main_screen();
    destroy_voice_recorder_ui();
    lv_obj_del(root);
}
// 手势事件回调
static void event_handler(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);

    if (code == LV_EVENT_GESTURE) {
        lv_indev_t *indev = lv_indev_get_act();
        if (!indev)
            return;

        lv_dir_t dir = lv_indev_get_gesture_dir(indev);

        // 右划或上划返回主界面
        if (dir == LV_DIR_RIGHT || dir == LV_DIR_TOP) {
            exit_voice_recorder_ui(e->target);
        }
    }
}

// 生成基于时间戳的唯一文件名
static void generate_filename(char *buf, size_t buf_size)
{
    time_t now;
    struct tm timeinfo;

    time(&now);
    localtime_r(&now, &timeinfo);

    // 确保目录存在
    struct stat st = { 0 };
    if (stat(VOICE_SD_PATH, &st) == -1) {
        mkdir(VOICE_SD_PATH, 0755);
    }

    // 格式: /sdcard/voice/YYYYMMDD_HHMMSS.wav
    strftime(buf, buf_size, VOICE_SD_PATH "/%Y%m%d_%H%M%S.wav", &timeinfo);
    ESP_LOGI(TAG, "Generated filename: %s", buf);
}

// 扫描SD卡中的录音文件
static int scan_recordings(char **files, int max_files)
{
    DIR *dir;
    struct dirent *ent;
    int count = 0;

    if ((dir = opendir(VOICE_SD_PATH)) != NULL) {
        while ((ent = readdir(dir)) != NULL && count < max_files) {
            // 检查文件扩展名是否为.wav
            if (strstr(ent->d_name, ".wav") != NULL) {
                files[count] = malloc(strlen(ent->d_name) + 1);
                if (files[count]) {
                    strcpy(files[count], ent->d_name);
                    count++;
                }
            }
        }
        closedir(dir);
    }

    return count;
}

/*
 *brief: 按修改时间排序文件列表
*/
static void sort_files_by_mtime(char **files, int count)
{
    struct stat st1, st2;

    for (int i = 0; i < count - 1; i++) {
        for (int j = i + 1; j < count; j++) {
            char path1[128], path2[128];
            snprintf(path1, sizeof(path1), VOICE_SD_PATH "/%s", files[i]);
            snprintf(path2, sizeof(path2), VOICE_SD_PATH "/%s", files[j]);

            if (stat(path1, &st1) == 0 && stat(path2, &st2) == 0) {
                if (st1.st_mtime < st2.st_mtime) {
                    // 交换文件指针
                    char *temp = files[i];
                    files[i] = files[j];
                    files[j] = temp;
                }
            }
        }
    }
}

// 刷新文件列表
static void refresh_file_list(void)
{
    // 清空当前列表
    lv_obj_clean(list);

    // 扫描SD卡中的录音文件
    char *files[20] = { 0 }; // 最多显示20个文件
    int file_count = scan_recordings(files, 20);

    if (file_count > 0) {
        // 按修改时间排序（最新的在前）
        sort_files_by_mtime(files, file_count);

        // 添加到列表
        for (int i = 0; i < file_count; i++) {
            lv_obj_t *btn = lv_list_add_btn(list, LV_SYMBOL_AUDIO, files[i]);
            lv_obj_add_event_cb(btn, list_btn_event_cb, LV_EVENT_CLICKED, NULL);
            free(files[i]); // 释放内存
        }
    } else {
        // 添加提示信息
        lv_obj_t *label = lv_label_create(list);
        lv_label_set_text(label, "无录音文件");
        lv_obj_set_style_text_color(label, lv_color_hex(0x888888), LV_PART_MAIN);
    }
}
static void check_filesystem_status(void);
// 录音任务
static void record_task(void *pvParameters)
{
    FILE *f = NULL;
    i2s_chan_handle_t i2s_rx_chan = get_i2s_rx_chan();
    i2s_chan_handle_t i2s_tx_chan = get_i2s_tx_chan();

    if (i2s_rx_chan == NULL) {
        ESP_LOGE(TAG, "I2S RX channel not available");
        vTaskDelete(NULL);
        return;
    }


    uint8_t *i2s_readraw_buff = NULL;
    size_t wav_written = 0;
    esp_err_t ret;
    // 分配读取缓冲区
    i2s_readraw_buff = malloc(I2S_READ_BUFFER_SIZE);
    if (i2s_readraw_buff == NULL) {
        ESP_LOGE(TAG, "Failed to allocate read buffer");
        vTaskDelete(NULL);
        return;
    }

    if (get_voice_control()) //有开启语音控制则提示用户
    {                        /*先关闭 语音控制*/
        app_sr_deinit();
    }
    voive_i2s_fs_init();

    while (1) {
        // 等待事件
        EventBits_t bits = xEventGroupWaitBits(s_voice_event_group,
                                               VOICE_ALL_BITS,
                                               pdTRUE, // 清除等待的事件位
                                               pdFALSE,
                                               portMAX_DELAY);

        if (bits & VOICE_EXIT_BIT) {
            break;
        }

        if (bits & VOICE_START_BIT) {
            // 生成唯一文件名
            generate_filename(file_path, sizeof(file_path));
            const char *filename_only = strrchr(file_path, '/');
            if (filename_only) {
                strlcpy(latest_filename, filename_only + 1, sizeof(latest_filename));
            } else {
                // 处理没有路径分隔符的情况
                strlcpy(latest_filename, file_path, sizeof(latest_filename));
            }

            ESP_LOGI(TAG, "Starting recording to: %s", file_path);

            // 打开文件
            f = fopen(file_path, "wb");
            if (f == NULL) {
                ESP_LOGE(TAG, "Failed to open file: %s", file_path);
                // 检查文件系统状态
                check_filesystem_status();
                continue;
            }

            // 跳过WAV文件头，预留空间
            if (fseek(f, sizeof(wav_header_t), SEEK_SET) != 0) {
                ESP_LOGE(TAG, "Failed to seek in file");
                fclose(f);
                f = NULL;
                continue;
            }

            wav_written = 0;
            is_recording = true;
            bool write_error = false;

            // 录音循环
            while (is_recording && !write_error) {
                // 检查是否有停止或退出事件
                bits = xEventGroupGetBits(s_voice_event_group);
                if (bits & VOICE_EXIT_BIT) {
                    is_recording = false;
                    // 不要清除VOICE_EXIT_BIT，让外层循环处理
                    break;
                }

                if (bits & VOICE_STOP_BIT) {
                    is_recording = false;
                    xEventGroupClearBits(s_voice_event_group, VOICE_STOP_BIT);
                    break;
                }

                // 采集音频数据
                size_t bytes_read = 0;
                /* Read RAW samples from ES7210 */
                 ret = i2s_channel_read(i2s_rx_chan, i2s_readraw_buff, I2S_READ_BUFFER_SIZE, &bytes_read,
                                                 pdMS_TO_TICKS(1000));

                if (ret != ESP_OK || bytes_read == 0) {
                    vTaskDelay(pdMS_TO_TICKS(10));
                    continue;
                }

                // 写入音频数据 - 使用更安全的写入方式
                size_t written = fwrite(i2s_readraw_buff, 1, bytes_read, f);
                if (written != bytes_read) {
                    ESP_LOGE(TAG, "File write error: written %d, expected %d", written, bytes_read);
                    write_error = true;
                    is_recording = false;
                    break;
                }

                // 定期刷新文件缓冲区，减少数据丢失风险
                if (wav_written % (I2S_READ_BUFFER_SIZE * 10) == 0) {
                    fflush(f);
                }

                wav_written += written;

                // 短暂让出CPU，避免饿死其他任务
                vTaskDelay(pdMS_TO_TICKS(1));
            }

            // 录音完成后写入正确的WAV文件头
            if (f && !write_error) {
                // 回到文件开头，写入正确的文件头
                if (fseek(f, 0, SEEK_SET) == 0) {
                    wav_header_t updated_header =
                        WAV_HEADER_PCM_DEFAULT(wav_written, VOICE_I2S_SAMPLE_BITS,
                                               VOICE_I2S_SAMPLE_RATE, VOICE_I2S_CHAN_NUM);

                    ESP_LOGI(TAG, "Wav header updated. Total bytes written: %d", wav_written);

                    if (fwrite(&updated_header, sizeof(wav_header_t), 1, f) != 1) {
                        ESP_LOGE(TAG, "Error while updating wav header");
                    }
                } else {
                    ESP_LOGE(TAG, "Failed to seek to file beginning for header update");
                }

                fclose(f);
                f = NULL;

                // 通知有新文件可用
                xEventGroupSetBits(s_voice_event_group, VOICE_NEW_FILE_BIT);
                lv_timer_ready(new_file_timer);//设置定时器就绪
            } else if (write_error) {
                // 写入错误时关闭并删除不完整的文件
                if (f) {
                    fclose(f);
                    f = NULL;
                    // 删除不完整的文件
                    unlink(file_path);
                    ESP_LOGE(TAG, "Deleted incomplete file due to write error: %s", file_path);
                }
            }

            ESP_LOGI(TAG, "Recording stopped. Wrote %d bytes to %s", wav_written,
                     write_error ? "none (error)" : file_path);
        } else if (bits & VOICE_PLAY_BIT){
               // 构建完整文件路径
               char full_path[128];
               const char *selected_filename = lv_list_get_btn_text(list, current_list_btn);
               snprintf(full_path, sizeof(full_path), VOICE_SD_PATH "/%s", selected_filename);
               ESP_LOGI(TAG, "open file: %s", full_path);
               // 打开文件
               f = fopen(full_path, "rb");
               if (f == NULL) {
                   ESP_LOGE(TAG, "Failed to open file for playback: %s", full_path);
                   fclose(f);
                   f = NULL;
                   continue;
               }
                // 读取WAV文件头部
                wav_header_t wav_header;
                size_t read_len = fread(&wav_header, 1, sizeof(wav_header_t), f);
                if (read_len != sizeof(wav_header_t)) {
                    ESP_LOGE(TAG, "Failed to read WAV header");
                    fclose(f);
                    f = NULL;
                    continue;
                }

                // 验证WAV文件格式
                if (memcmp(wav_header.descriptor_chunk.chunk_id, "RIFF", 4) != 0 ||
                    memcmp(wav_header.descriptor_chunk.chunk_format, "WAVE", 4) != 0 ||
                    memcmp(wav_header.fmt_chunk.subchunk_id, "fmt ", 4) != 0 ||
                    memcmp(wav_header.data_chunk.subchunk_id, "data", 4) != 0) {
                    ESP_LOGE(TAG, "Invalid WAV file format");
                    fclose(f);
                    f = NULL;
                    continue;
                }

                // 检查音频格式
                if (wav_header.fmt_chunk.audio_format != 1) { // 1 = PCM
                    ESP_LOGE(TAG, "Unsupported audio format: %d (only PCM supported)", wav_header.fmt_chunk.audio_format);
                    fclose(f);
                    f = NULL;
                    continue;
                }
                ESP_LOGI(TAG, "sample_rate: %d, bits_per_sample: %d, num_of_channels: %d", wav_header.fmt_chunk.sample_rate, wav_header.fmt_chunk.bits_per_sample, wav_header.fmt_chunk.num_of_channels);
                // 配置I2S用于播放
                bsp_codec_set_fs(wav_header.fmt_chunk.sample_rate, wav_header.fmt_chunk.bits_per_sample, wav_header.fmt_chunk.num_of_channels);
                size_t play_bytes_read = 0;
                size_t play_total_bytes_read = 0;
                uint32_t play_data_size = wav_header.data_chunk.subchunk_size;
                ESP_LOGI(TAG, "Playing file size : %d", play_data_size);
                bsp_codec_volume_set(80,NULL);
                pa_en(1); // 使能功放
                /* 禁用并预加载首块数据 */
                // //!这里默认i2s是禁止的，
                // i2s_channel_disable(i2s_tx_chan); // I2S_CHAN_STATE_READY
                //                                   // 计算本次读取的数据量
                size_t to_read = MIN(I2S_READ_BUFFER_SIZE, play_data_size - play_total_bytes_read);

                // // 读取音频数据
                // play_bytes_read = fread(i2s_readraw_buff, 1, to_read, f);

                // //todo这里应该判断是否成功
                // ESP_ERROR_CHECK(i2s_channel_preload_data(i2s_tx_chan, i2s_readraw_buff, play_bytes_read, &to_read));
                // play_total_bytes_read += play_bytes_read;
                // ESP_ERROR_CHECK(i2s_channel_enable(i2s_tx_chan));
                // 写入I2S发送通道
                size_t bytes_written = 0;
                // 播放循环
                while (play_total_bytes_read < play_data_size) {
                    // 检查是否有停止或退出事件
                    bits = xEventGroupGetBits(s_voice_event_group);
                    if (bits & VOICE_EXIT_BIT || bits & VOICE_PLAY_BIT) {
                        // 不要清除VOICE_EXIT_BIT，让外层循环处理
                        break;
                    }

                    if (bits & VOICE_STOP_BIT) {
                        xEventGroupClearBits(s_voice_event_group, VOICE_STOP_BIT);
                        break;
                    }


                    // 计算本次读取的数据量
                     to_read = MIN(I2S_READ_BUFFER_SIZE, play_data_size - play_total_bytes_read);

                    // 读取音频数据
                    play_bytes_read = fread(i2s_readraw_buff, 1, to_read, f);
                    //ESP_LOGI(TAG, "play_bytes_read: %d", play_bytes_read);
                    if (play_bytes_read == 0) {
                        ESP_LOGI(TAG, "End of file reached");
                        // 文件结束或读取错误

                        break;
                    }


                    ret = i2s_channel_write(i2s_tx_chan, i2s_readraw_buff, play_bytes_read, &bytes_written, pdMS_TO_TICKS(1000));
                    //ESP_LOGI(TAG, "bytes_written: %d", bytes_written);
                    if (ret != ESP_OK) {
                        ESP_LOGE(TAG, "I2S write error during playback: %d", ret);
                        break;
                    }

                    play_total_bytes_read += play_bytes_read;

                    // 短暂让出CPU
                    vTaskDelay(pdMS_TO_TICKS(1));
                }
                if (play_total_bytes_read == play_data_size)
                {
                    // 停止录音
                    is_recording = false;
                    lv_obj_clear_state(rec_button, LV_STATE_CHECKED);
                    lv_timer_pause(waveform_timer);
                    lv_label_set_text(rec_label, LV_SYMBOL_PLAY);                                // 切换为播放图标
                    lv_obj_set_style_bg_color(rec_button, lv_color_hex(0x00FF00), LV_PART_MAIN); // 按钮变绿色
                    xEventGroupSetBits(s_voice_event_group, VOICE_STOP_BIT);
                }
                pa_en(0); // 关闭功放
                fclose(f);
                f = NULL;
        }
    }

    // 清理资源
    if (f) {
        fclose(f);
    }

    if (i2s_readraw_buff) {
        free(i2s_readraw_buff);
        i2s_readraw_buff = NULL;
    }

    if (get_voice_control()) //有开启语音控制则提示用户
    {
        // 重新初始化语音控制
        app_sr_init();
    }

    vTaskDelete(NULL);
}

// 添加文件系统状态检查函数
static void check_filesystem_status(void)
{
    // 这里可以添加检查存储设备状态和可用空间的代码
    ESP_LOGI(TAG, "Checking filesystem status...");
    // 示例: 检查可用空间
    // struct statvfs buf;
    // if (statvfs("/sdcard", &buf) == 0) {
    //     uint64_t free_size = (uint64_t)buf.f_bsize * buf.f_bfree;
    //     ESP_LOGI(TAG, "Free space: %llu bytes", free_size);
    //     if (free_size < MIN_FREE_SPACE) {
    //         ESP_LOGE(TAG, "Insufficient storage space");
    //     }
    // }
}

// 波形更新定时器回调
static void waveform_timer_cb(lv_timer_t *timer)
{
    if (!is_recording)
        return;

    // 模拟添加随机数据点到波形图
    lv_chart_set_next_value(waveform_chart, ser, lv_rand(10, 100));

    // 更新时间
    rec_seconds++;
    uint32_t minutes = rec_seconds / 60;
    uint32_t seconds = rec_seconds % 60;
    lv_label_set_text_fmt(time_label, "%02lu:%02lu", minutes, seconds);
}

// 检查新文件的定时器回调
static void check_new_file_timer_cb(lv_timer_t *timer)
{
    EventBits_t bits = xEventGroupGetBits(s_voice_event_group);
    if (bits & VOICE_NEW_FILE_BIT) {
        xEventGroupClearBits(s_voice_event_group, VOICE_NEW_FILE_BIT);

        // 刷新文件列表以显示新文件
        refresh_file_list();

        ESP_LOGI(TAG, "Added new file to list: %s", latest_filename);
    }
}

// 录音按钮事件处理
static void rec_button_event_cb(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);

    if (code == LV_EVENT_CLICKED) {
        if (!is_recording) {
            // 开始录音
            is_recording = true;
            rec_seconds = 0;                                // 重置计时器
            lv_label_set_text(time_label, "00:00");         // 重置时间显示
            lv_obj_add_state(rec_button, LV_STATE_CHECKED); // 按键变红
            lv_timer_resume(waveform_timer);
            lv_label_set_text(rec_label, LV_SYMBOL_STOP);                                // 切换为停止图标
            lv_obj_set_style_bg_color(rec_button, lv_color_hex(0xFF0000), LV_PART_MAIN); // 按钮变红色
            xEventGroupSetBits(s_voice_event_group, VOICE_START_BIT);
        } else {
            // 停止录音
            is_recording = false;
            lv_obj_clear_state(rec_button, LV_STATE_CHECKED);
            lv_timer_pause(waveform_timer);
            lv_label_set_text(rec_label, LV_SYMBOL_PLAY);                                // 切换为播放图标
            lv_obj_set_style_bg_color(rec_button, lv_color_hex(0x00FF00), LV_PART_MAIN); // 按钮变绿色
            xEventGroupSetBits(s_voice_event_group, VOICE_STOP_BIT);
        }
    }
}

// 列表项点击事件处理
static void list_btn_event_cb(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);

    if (code == LV_EVENT_CLICKED) {
        lv_obj_t *btn = lv_event_get_target(e);
        current_list_btn = btn;
       // const char *filename = lv_list_get_btn_text(list, btn);

        // 构建完整文件路径
        // char full_path[128];
        // snprintf(full_path, sizeof(full_path), VOICE_SD_PATH "/%s", filename);

        // 调用播放器播放选中的音频文件
       // ESP_LOGI(TAG, "Playing audio file: %s", full_path);
        // play_audio_file(full_path);                                                  // 假设有这个函数
        if (is_recording)
            return;
        lv_label_set_text(rec_label, LV_SYMBOL_PAUSE);                           // 切换为暂停图标
        lv_obj_set_style_bg_color(rec_button, lv_color_hex(0x0000FF), LV_PART_MAIN); // 按钮变蓝色
        xEventGroupSetBits(s_voice_event_group, VOICE_PLAY_BIT);
    }
}

// 创建录音机UI
lv_obj_t *create_voice_recorder_ui(void)
{
    // 创建根容器（全屏黑色背景）
    lv_obj_t *root = lv_obj_create(NULL);
    if (!root)
        return NULL;

    lv_obj_set_size(root, 320, 240); // 固定尺寸适配320x240屏幕
    lv_obj_set_style_bg_color(root, lv_color_black(), LV_PART_MAIN);
    lv_obj_set_style_border_width(root, 0, LV_PART_MAIN);
    lv_obj_set_style_pad_all(root, 0, LV_PART_MAIN);
    lv_obj_add_event_cb(root, event_handler, LV_EVENT_GESTURE, NULL);
    if (bsp_sdcard_mount() != ESP_OK) {
        ESP_LOGE(TAG, "Failed to mount SD card");
        // 显示提示信息
        lvgl_port_lock(0);
        lv_obj_t *label_voice_err = lv_label_create(root);
        lv_label_set_text(label_voice_err, "SD卡挂载失败");
        lv_obj_set_style_text_color(label_voice_err, lv_color_white(), 0);
        lv_obj_set_style_text_font(label_voice_err, &myFont, 0);
        lv_obj_align(label_voice_err, LV_ALIGN_CENTER, 0, -50);
        lvgl_port_unlock();
        return root;
    }

    // 确保录音目录存在
    struct stat st = { 0 };
    if (stat(VOICE_SD_PATH, &st) == -1) {
        mkdir(VOICE_SD_PATH, 0755);
    }
    // 创建事件组
    if (s_voice_event_group == NULL) {
        s_voice_event_group = xEventGroupCreate();
        if (s_voice_event_group == NULL) {
            ESP_LOGE(TAG, "Event group create failed");
            lv_obj_del(root);
            return NULL;
        }
    }
    // 创建标题
    lv_obj_t *title = lv_label_create(root);
    lv_label_set_text(title, "录音机");
    lv_obj_set_style_text_color(title, lv_color_white(), LV_PART_MAIN);
    lv_obj_set_style_text_font(title, &myFont, LV_PART_MAIN);
    lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 5); // 上边距减小

    // 创建录音文件列表
    list = lv_list_create(root);
    lv_obj_set_size(list, 300, 70);              // 固定尺寸
    lv_obj_align(list, LV_ALIGN_TOP_MID, 0, 35); // 位置调整
    lv_obj_set_style_bg_color(list, lv_color_black(), LV_PART_MAIN);
    lv_obj_set_style_border_color(list, lv_color_hex(0x333333), LV_PART_MAIN);
    lv_obj_set_style_text_font(list, &myFont, LV_PART_MAIN);

    // 刷新文件列表
    refresh_file_list();

    // 创建小型波形图
    waveform_chart = lv_chart_create(root);
    lv_obj_set_size(waveform_chart, 200, 40); // 较小的波形图
    lv_obj_align(waveform_chart, LV_ALIGN_TOP_MID, 0, 120);
    lv_chart_set_type(waveform_chart, LV_CHART_TYPE_LINE);
    lv_chart_set_range(waveform_chart, LV_CHART_AXIS_PRIMARY_Y, 0, 100);
    lv_chart_set_point_count(waveform_chart, 30); // 减少点数
    lv_chart_set_div_line_count(waveform_chart, 0, 0);
    lv_obj_set_style_bg_color(waveform_chart, lv_color_black(), LV_PART_MAIN);
    lv_obj_set_style_border_width(waveform_chart, 0, LV_PART_MAIN);
    lv_obj_set_style_line_color(waveform_chart, lv_color_hex(0x00C6FF), LV_PART_MAIN);
    lv_obj_set_style_line_width(waveform_chart, 2, LV_PART_MAIN);
    lv_obj_set_style_size(waveform_chart, 0, LV_PART_INDICATOR);

    ser = lv_chart_add_series(waveform_chart, lv_color_hex(0x00C6FF), LV_CHART_AXIS_PRIMARY_Y);

    // 创建时间显示
    time_label = lv_label_create(root);
    lv_label_set_text(time_label, "00:00");
    lv_obj_set_style_text_color(time_label, lv_color_white(), LV_PART_MAIN);
    lv_obj_set_style_text_font(time_label, &myFont, LV_PART_MAIN);
    lv_obj_align(time_label, LV_ALIGN_TOP_MID, 0, 160);

    // 创建控制按钮容器
    lv_obj_t *btn_cont = lv_obj_create(root);
    lv_obj_set_size(btn_cont, 300, 50);
    lv_obj_align(btn_cont, LV_ALIGN_TOP_MID, 0, 195);
    lv_obj_set_style_bg_color(btn_cont, lv_color_black(), LV_PART_MAIN);
    lv_obj_set_style_border_width(btn_cont, 0, LV_PART_MAIN);
    lv_obj_set_flex_flow(btn_cont, LV_FLEX_FLOW_ROW);
    lv_obj_set_flex_align(btn_cont, LV_FLEX_ALIGN_SPACE_EVENLY, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);

    // 创建录音按钮
    rec_button = lv_btn_create(btn_cont);
    lv_obj_set_size(rec_button, 55, 40); // 较小的按钮
    lv_obj_add_event_cb(rec_button, rec_button_event_cb, LV_EVENT_ALL, NULL);
    lv_obj_set_style_bg_color(rec_button, lv_color_hex(0x00FF00), LV_PART_MAIN); // 初始为绿色

    rec_label = lv_label_create(rec_button);
    lv_obj_set_style_text_font(rec_label, &lv_font_montserrat_14, LV_PART_MAIN);
    lv_label_set_text(rec_label, LV_SYMBOL_PLAY);
    lv_obj_center(rec_label);

    // 创建波形更新定时器（初始暂停）
    waveform_timer = lv_timer_create(waveform_timer_cb, 1000, NULL);
    lv_timer_pause(waveform_timer);

    // 创建检查新文件的定时器
    new_file_timer = lv_timer_create(check_new_file_timer_cb, 500, NULL);

    // 重置录音状态
    is_recording = false;
    rec_seconds = 0;

    // 创建录音任务
    if (voice_task_Handle == NULL) {
        //xTaskCreate(record_task, "record_task", 6 * 1024, NULL, 5, &voice_task_Handle);
        xTaskCreateWithCaps(record_task, "record_task", 8 * 1024, NULL, 5, NULL, MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
    }

    return root;
}

// 销毁录音机UI
void destroy_voice_recorder_ui(void)
{
    // 发送退出信号
    if (s_voice_event_group) {
        xEventGroupSetBits(s_voice_event_group, VOICE_EXIT_BIT);
    }

    // 等待任务退出
    if (voice_task_Handle) {
        // 等待300ms
        vTaskDelay(pdMS_TO_TICKS(300));
        voice_task_Handle = NULL;
    }
    // 删除事件组
    if (s_voice_event_group) {
        vEventGroupDelete(s_voice_event_group);
        s_voice_event_group = NULL;
    }

    // 停止定时器
    if (waveform_timer) {
        lv_timer_del(waveform_timer);
        waveform_timer = NULL;
    }

    if (new_file_timer) {
        lv_timer_del(new_file_timer);
        new_file_timer = NULL;
    }

    // 卸载SD卡（
    bsp_sdcard_unmount();
}